﻿using CPPEI.ETL.DataServiceInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace CPPEI.ETL.DSImplement.WS
{
    /// <summary>
    /// 适用于此结构的xml数据
    /// <![CDATA[
    ///     <xml>
    ///         <data>
    ///             <column1>value</column1>
    ///             <column1>value</column1>
    ///         </data>
    ///         <data>
    ///             <column1>value</column1>
    ///             <column1>value</column1>
    ///         </data>
    ///     </xml>
    /// ]]>
    /// </summary>
    public class XmlNodeData : IData
    {
        public DataType Type
        {
            get;
            private set;
        }

        public object Data
        {
            get;
            private set;
        }

        private XmlNode _xmlNode;
        private int _total;
        private string _rootXPath;
        private List<Column> _columns;

        public XmlNodeData(XmlNode data)
        {
            Type = DataType.XmlNode;
            Data = data;
            _xmlNode = data;
            
            List<string> names;
            List<Type> types;

            if (!WSTypeUtil.XmlNodeUtil.Parse("RET", _xmlNode, out _rootXPath, out names, out types, out _total))
            {
                throw new WS.WSNotSupportException();
            }

            _columns = new List<Column>();
            for (int index = 0; index < names.Count; index++)
            {
                Column column = new Column(names[index].Split(new char[] { '.' }).Last(), names[index], types[index]);
                _columns.Add(column);
            }
            _total = _xmlNode.SelectNodes(_rootXPath).Count;
        }

        public List<Column> GetSchema()
        {
            return _columns;
        }
        public int RowCount
        {
            get { return _total; }
        }

        public Row Get(int index)
        {
            List<Column> columns = GetSchema();

            Row row = new Row(index);

            XmlNodeList xChildren = _xmlNode.SelectNodes(_rootXPath);
            XmlNode xChild = xChildren[index];

            // column.Name: RET.xxx.xxx.xxx.LEAF
            // _rootXPath: ./xxx/xxx/
            string xRelativeRoot = WSTypeUtil.XmlNodeUtil.GetXPath(xChild);
            for (int colIndex = 0; colIndex < columns.Count; colIndex++)
            {
                string xFullPath = columns[colIndex].Path.Replace(".", "/").Replace("RET/", string.Empty);
                string xRelativePath = xFullPath.Replace(xRelativeRoot, "./");
                string value = WSTypeUtil.XmlNodeUtil.GetValue(xChild, xRelativePath);
                Row.Add(row, columns[colIndex].Name, value);
            }

            return row;
        }
    }
}
